const express = require('express');
const path = require('path');
const fs = require('fs');
const static = require('express-static');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const bodyParser = require('body-parser');  //只能解析post数据 不能解析post文件
const multer  = require('multer'); //解析上传的文件
const mysql = require('mysql');
const cors = require('cors');

let banners = require('./server/router/banner');
let nav = require('./server/router/nav');
let bigshot = require('./server/router/bigshot');
let recommend = require('./server/router/recommend');
let add = require('./server/router/add');
let detail = require('./server/router/detail');
let updata = require('./server/router/updata');
let del = require('./server/router/del');



let objMulter = multer({dest:'./www/updata/'});//保存到路径

const server = express();

//引用bodyParser 解析post数据
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({
  extended: true
}));

   // 解决跨域问题
   server.all("/*", function(req, res, next) {
    // 跨域处理
    res.header("Access-Control-Allow-Origin", "*");
   //  res.header("Access-Control-Allow-Headers", "X-Requested-With");
   res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next(); // 执行下一个路由
   });

//1.解析cookie

let keys = ['aa,','bb','cc'];
server.use(cookieParser('abcdefg'))
// //2.使用session
server.use(cookieSession({name:"sid",keys,maxAge:20*3600*1000}));
//轮播
server.use(banners());
//导航图标
server.use(nav());
//打咔
server.use(bigshot());
//推荐列表
server.use(recommend());
  //添加
server.use(add());
  //详情查询
  server.use(detail());
   //编辑操作
   server.use(updata());
     //删除操作
     server.use(del());
//图片上传
server.use(objMulter.any());//any 处理任何文件
// server.use(files());
server.use('/files',(req,res,next)=>{
   
   //文件名字
   let filename = req.files[0].filename
    //     // //获取文件名
    let originName =req.files[0].path + path.parse(req.files[0].originalname).ext;
    //ngingx代理图片 整体的路径上传到mysql
    let http = req.protocol + '://127.0.0.1:12000/updata/'+`${filename}${path.parse(req.files[0].originalname).ext}`;

    // //重命名
    fs.rename(req.files[0].path,originName,(err)=>{
       
      if(err){
//         // 上传失败
         res.status(500).send('上传失败').end();
      }else{
//            //    上传成功
       res.status(200).send({imgsrc:http}).end();
      }
      next()
  })


})

server.listen(8787,()=>{console.log('我已启动')});

